package com.guoliang.oss.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guoliang.oss.service.OssService;
import com.guoliang.oss.utils.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author ：Leo
 * @date ：Created in 2023/1/17 10:24
 * @description：
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        //uuid拼接文件名 保证文件名唯一
        String fileName = file.getOriginalFilename();
        String uuid= UUID.randomUUID().toString().replace("-","");
        String date = DateUtil.format(new Date(), "yyyy/MM/dd");
        fileName=date+"/"+uuid+fileName;
        try {
            //创建oss实例
            OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
           // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, fileName,inputStream);
            ossClient.shutdown();
            //拼接url返回
//            https://edu-3255.oss-cn-hangzhou.aliyuncs.com/liudehua.png
            String url="https://"+bucketName+"."+endpoint+"/"+ fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
